package cn.b.sky.user.service.impl;

import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.TreeInterface;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.common.utils.TreeUtil;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.dao.RoleDao;
import cn.b.sky.user.dao.UserDao;
import cn.b.sky.user.service.RoleService;
import cn.b.sky.user.service.model.*;
import cn.b.sky.user.service.model.condition.RoleCondition;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.util.List;

@Service("roleService")
public class RoleServiceImpl implements RoleService {

    private static final Logger LOG = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Resource
    RoleDao roleDao;

    @Resource
    UserDao userDao;

    @Override
    public int selectRoleCount(RoleCondition roleCondition) {
        if (roleCondition != null) {
            return roleDao.selectRoleCount(roleCondition);
        } else {
            return 0;
        }
    }

    @Override
    public List<Role> selectRoleList(RoleCondition roleCondition) {
        return roleDao.selectRoleList(roleCondition);
    }

    @Override
    public Role selectRole(String siteCode, String roleCode) {
        return roleDao.selectRole(siteCode, roleCode);
    }

    @Override
    public void insertRole(Role role) {
        roleDao.insertRole(role);
//		if (role.getMenus() != null && role.getMenus().size() > 0)
//		{
//			for (RoleMenu m : role.getMenus())
//			{
//				roleDao.insertRoleMenu(m);
//			}
//		}
        if (role.getUsers() != null && role.getUsers().size() > 0) {
            for (UserRole u : role.getUsers()) {
                userDao.insertUserRole(u);
            }
        }
    }

    @Override
    public void updateRole(Role role) {
        roleDao.updateRole(role);
        //roleDao.deleteRoleMenu(role.getSiteCode(), role.getRoleCode());
        roleDao.deteteUserRoleByRole(role.getSiteCode(), role.getRoleCode());

//		if (role.getMenus() != null && role.getMenus().size() > 0)
//		{
//			for (RoleMenu m : role.getMenus())
//			{
//				roleDao.insertRoleMenu(m);
//			}
//		}
        if (role.getUsers() != null && role.getUsers().size() > 0) {
            for (UserRole u : role.getUsers()) {
                userDao.insertUserRole(u);
            }
        }
    }

    @Override
    public BatchJobReport deleteRole(String siteCode, String roleCode) {
        String cause = "";
        Boolean success = true;
        try {
            roleDao.deleteRoleMenu(siteCode, roleCode);
            roleDao.deteteUserRoleByRole(siteCode, roleCode);
            roleDao.deleteRole(siteCode, roleCode);
        } catch (Exception e) {
            LOG.error("{}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            if (DatabaseUtils.isConstraintsError(e.getMessage())) {
                // 外键删除已存在提示
                cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(), SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M") + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(), SecurityContextUtil.getLanguageCode(), "notDelete.M");
            } else {
                cause = e.getMessage();
            }
            success = false;
        }
        return new BatchJobReport(roleCode, cause, success, SecurityContextUtil.getLanguageCode(), SecurityContextUtil.getSiteCode());

    }

    @Override
    public List<TreeInterface> selectMenuByRole(String siteCode, String roleCode) {
        List<Menu> menus = roleDao.selectMenuByRole(siteCode, roleCode);
        return TreeUtil.gradingRecursion(menus.toArray(new Menu[menus.size()]), null);
    }

    @Override
    public List<UserInfo> selectUserByRole(String siteCode, String roleCode) {
        return roleDao.selectUserByRole(siteCode, roleCode);
    }

    @Override
    public List<RoleBusinessType> selectRoleBusinessTypeByRole(String siteCode, String roleCode) {
        if (!StringUtils.isEmpty(siteCode) && !StringUtils.isEmpty(roleCode)) {
            return this.roleDao.selectRoleBusinessTypeByRole(siteCode, roleCode);
        }
        return null;
    }

    @Override
    public void saveRoleBusinessType(Role role) {
        if (role != null) {
            for (RoleBusinessType r : role.getRoleBusinessTypes()) {
                r.setSiteCode(role.getSiteCode());
                r.setRoleCode(role.getRoleCode());
                RoleBusinessType roleBusinessType = roleDao.selectRoleBusinessTypeByPk(r.getSiteCode(), r.getRoleCode(), r.getBusinessType());
                if (roleBusinessType != null && !StringUtils.isBlank(roleBusinessType.getBusinessType())) {
                    roleDao.updateRoleBusinessType(r);
                } else {
                    roleDao.insertRoleBusinessType(r);
                }
            }
        }
    }

    @Override
    @Transactional
    public void authorizeRole(Role role) {
        roleDao.deleteRoleMenu(role.getSiteCode(), role.getRoleCode());
        if (role.getMenus() != null && role.getMenus().size() > 0) {
            roleDao.batchInsertRoleMenu(role);
        }
    }

}
